<template>
  <div>
    <el-card shadow="always" :body-style="{padding:'20px'}">
      <!--      表头-->
      <template #header>
        <el-button v-has="'btn.Trademark.add'" type="primary" icon="ele-Plus" @click="addTradeMarkItem">添加</el-button>

        <!--        Dialog 弹出一个对话框-->
        <el-dialog
            v-model="isDialog"
            :title="formLabelAlign?.id?'修改品牌':'添加品牌'"
            width="30%"
        >
          <!--          内容区域-->
          <el-form
              label-width="100px"
              :model="formLabelAlign"
              style="max-width: 460px"
              :rules="rules"
              ref="formEle"
          >
            <el-form-item label="标题" prop="tmName" style="width: 80%">
              <el-input v-model="formLabelAlign.tmName"/>
            </el-form-item>
            <!--            照片上传-->
            <el-form-item label="品牌LOGO" prop="logoUrl" style="width: 80%">
              <el-upload
                  class="avatar-uploader"
                  :action="`${baseUrl}/admin/product/upload`"
                  :show-file-list="false"
                  :on-success="Success"
                  :before-upload="beforeAvatarUpload"
              >
                <img v-if="formLabelAlign.logoUrl" :src="formLabelAlign.logoUrl" class="avatar"/>
                <el-icon v-else class="avatar-uploader-icon">
                  <ele-Plus/>
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-form>

          <template #footer>
             <span class="dialog-footer">
               <el-button @click="noAdd">取消</el-button>
               <el-button type="primary" @click="addTrademarkItem">
                 保存
               </el-button>
             </span>
          </template>
        </el-dialog>

      </template>
      <!--      表单-->
      <el-table :data="trademarkList" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="80"/>
        <el-table-column prop="tmName" label="品牌名称"/>
        <el-table-column label="品牌Logo">
          <template v-slot="{row}">
            <div>
              <el-image
                  :preview-src-list="[row.logoUrl]"
                  :preview-teleported="true"
                  style="width:100px"
                  :src="row.logoUrl" fit="fill"
                  :lazy="true">

              </el-image>
            </div>
          </template>
        </el-table-column>
        >
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button @click="fixTrademark(row)" type="warning" size="small" icon="ele-Edit"
                       v-has="'btn.Trademark.update'">修改
            </el-button
            >
            <el-button type="danger" @click="deleteTradeMarkItem(row)" size="small" icon="ele-Delete"
                       v-has="'btn.Trademark.remove'">删除
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!--      分页器-->
      <el-pagination
          :background="true"
          v-model:page-size="count"
          v-model:current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      />
    </el-card>
  </div>
</template>

<script lang="ts">
import {defineComponent} from "vue";

export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
// 品牌管理数据
import {onMounted, reactive, ref, watch} from "vue";
import {
  type RecordsType, reqDeleteTrademarkItemAsync,
  reqGetTrademarkListAsync,
  reqPostTrademarkItemAsync,
  reqPutTrademarkItemAsync
} from "@/api/trademark";
import {ElMessage, type FormRules, type UploadProps} from "element-plus/es";

const trademarkList = ref<RecordsType[]>([]);

// page-size 每页显示的条目个数
const count = ref(10)

// 当前页数
const currentPage = ref(1)

// 总页数
let total = ref<number>(1)

// 获取品牌列表数据
const getTrademarkList = async () => {
  try {
    const result = await reqGetTrademarkListAsync(currentPage.value, count.value);
    total.value = result.total
    trademarkList.value = result.records
  } catch (e) {
    alert('获取数据失败')
  }
}

// 挂载时获取trademark列表数据
onMounted(() => {
  getTrademarkList()
})

// 监听 每页显示的条目个数和当前页数的改变
watch([count, currentPage], () => {
  // 实时获取数据
  getTrademarkList()
})

// ------------------------------------------------------------------------
// 控制弹出框的显示和隐藏
let isDialog = ref<boolean>(false)

// 收集的表单数据
const formLabelAlign = ref<RecordsType>({
  logoUrl: '',
  tmName: ''
})

// 失焦时表单的单独校验
const rules = reactive<FormRules>({
  tmName: [
    {required: true, message: '品牌名不能为空', trigger: 'blur'},
  ],
  logoUrl: [
    {required: true, message: '图片不能为空', trigger: 'blur'},
  ]
})

//因为上传需要发送请求，且不经过我们的axios，所以需要修改请求地址
const baseUrl = import.meta.env.VITE_API_URL;

// 照片上传成功的回调
const Success = (response: any) => {
  // 返回一个可以在线查看图片的地址
  formLabelAlign.value.logoUrl = response.data
}

// 照片上传失败的回调
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('头像图片必须是JPG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像图片大小大于2mb')
    return false
  }
  return true
}

// 获取el-form组件的 DOM对象
const formEle = ref()


// 点击添加
const addTradeMarkItem = () => {
  // 开启弹窗
  isDialog.value = true;
  // 清空表单(点修改再点添加form有数据)
  formLabelAlign.value = {
    tmName: '',
    logoUrl: ''
  }

  // 每次检验的时候 清除前一个校验
  formEle.value?.resetFields()
}

// 添加或修改品牌
const addTrademarkItem = async () => {

  // 提交时 表单的整体校验
  const re = await formEle.value?.validate(() => {
  });  // 这里加函数 就为了处理警告中的没有处理报错
  if (!re) return

  // 添加或修改
  try {
    if (!formLabelAlign.value.id) {  // 没有id 代表添加
      // 添加
      await reqPostTrademarkItemAsync(formLabelAlign.value)
      // 提示
      ElMessage.success('添加成功')
      // 重置已经添加过的数据
      formLabelAlign.value = {
        logoUrl: '',
        tmName: ''
      }
    } else {  // 有id  代表修改
      // 修改
      await reqPutTrademarkItemAsync(formLabelAlign.value)
      // 提示
      ElMessage.success('修改成功')

    }
    //关闭弹窗
    isDialog.value = false;

    // 刷新页面
    await getTrademarkList()

  } catch (e) {
    ElMessage.error(formLabelAlign.value.id ? '修改失败' : '添加失败')
  }
}

// 收集修改品牌信息
const fixTrademark = async (row: RecordsType) => {
  // 显示弹窗
  isDialog.value = true;
  formLabelAlign.value = {
    ...row
  }

  // 每次检验的时候 清除前一个校验
  formEle.value?.resetFields()
}

// 取消修改或添加
const noAdd = () => {
  // 隐藏弹窗
  isDialog.value = false;
  // 重置数据
  formLabelAlign.value = {
    logoUrl: '',
    tmName: ''
  }
}

// -------------------------------------------------------------------------
// 删除功能
const deleteTradeMarkItem = async (row: RecordsType) => {
  try {
    // alert('是否要删除吗')
    await reqDeleteTrademarkItemAsync(row.id as number);
    ElMessage.success('删除成功')
    // 刷新页面
    await getTrademarkList()
  } catch (e) {
    ElMessage.error('删除失败')
  }
}
</script>

<!--配合的css 在element-plus中查找-->
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-pagination {
  justify-content: center;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>